package controlLayer;
import modelLayer.PersonContainer;
import modelLayer.LoanContainer;
import modelLayer.DVDContainer;
import modelLayer.Person;
import modelLayer.DVD;
import modelLayer.Loan;
import modelLayer.Copy;
import modelLayer.PartLoan;
import java.util.ArrayList;
/**
 * Lav en beskrivelse af klassen LoanCtr her.
 * 
 * @author (dit navn her)
 * @version (versions nummer eller dato her)
 */
public class LoanCtr
{
    // instansvariabler - erstat eksemplet herunder med dine egne variabler
    private LoanContainer loanContainer;
    private PersonContainer personContainer;
    private DVDContainer dvdContainer;

    /**
     * Konstruktør for objekter af klassen LoanCtr
     */
    public LoanCtr()
    {
        loanContainer = LoanContainer.getInstance();
        personContainer = PersonContainer.getInstance();
        dvdContainer = DVDContainer.getInstance();
    }

    public void createLoan(String phoneNumber, ArrayList<String> dvdSerialNumbers, String period)
    {
        Person p = personContainer.findPerson(phoneNumber);
        Loan l = new Loan(0, period, "dags dato", p);
        
        for(String serialNumber : dvdSerialNumbers)
        {
            Copy c = dvdContainer.findCopy(serialNumber);
            PartLoan ep = loanAlreadyContainsDVD(l, c);
            
            if(ep != null){
                ep.addCopy(c);
            }else{
            PartLoan partLoan = new PartLoan(p, l);
            partLoan.addCopy(c);
            l.addPartLoan(partLoan);}   
        }
        p.addLoan(l);
        loanContainer.addLoan(l);
    }
    
    private PartLoan loanAlreadyContainsDVD(Loan loan, Copy copy)
    {
        for(PartLoan partLoan : loan.getPartLoans())
        {
            if(partLoan.getDVD() == copy.getDVD())
            {
                return partLoan;
            }
        }
        return null;
    }
    
    public void returnCopy(String serialNumber)
    {
        Copy copy = dvdContainer.findCopy(serialNumber);
        PartLoan partLoan = loanContainer.getPartLoanWithCopy(copy);
        Loan l = partLoan.getLoan();
        Person p = partLoan.getPerson();
        partLoan.removeCopy(copy);
        if(partLoan.isEmpty())
        {
            l.removePartLoan(partLoan);
        }
        if(l.isEmpty())
        {
            loanContainer.removeLoan(l);
            p.removeLoan(l);
        }
        
    }
    
    public boolean copyIsLentOut(String serialNumber)
    {
        return dvdContainer.findCopy(serialNumber).isLentOut();
    }
}
